package com.sprucetec.livechat.mcq.process;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sprucetec.livechat.common.NettyMessageDto;
import com.sprucetec.livechat.service.impl.ChatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName NettyMessageProcess
 * @Description:
 * @Author Kenny
 * @Date 2020/4/9
 **/

@Component("nettyMessageProcess")
public class NettyMessageProcess {

    @Autowired
    private ChatServiceImpl chatService;


    /**
     * 发送组消息
     *
     * @param jsonObject
     */
    public void processChatMessage(String jsonObject) {
        if (StringUtils.isBlank(jsonObject)) {
            return;
        }
        NettyMessageDto messageDto = JSONObject.parseObject(JSON.parse(jsonObject).toString(), NettyMessageDto.class);
        chatService.groupSendByMq(messageDto);
    }

    /**
     * 关闭连接
     *
     * @param jsonObject
     */
    public void processChannelClose(String jsonObject) {
        if (StringUtils.isBlank(jsonObject)) {
            return;
        }
        NettyMessageDto messageDto = JSONObject.parseObject(jsonObject, NettyMessageDto.class);
        chatService.removeChannelByMq(messageDto);
    }

    /**
     * 关闭直播
     */
    public void processCloseVideo(String jsonObject) {
        if (StringUtils.isBlank(jsonObject)) {
            return;
        }
        NettyMessageDto messageDto = JSONObject.parseObject(jsonObject, NettyMessageDto.class);
        chatService.liveServerSendByMq(messageDto);
    }

    public void sendOnlineUser(String messageBody) {
        sendOnlineUser(messageBody, false);
    }

    public void sendOnlineUser(String messageBody, boolean isAway) {
        if (StringUtils.isBlank(messageBody)) {
            return;
        }
        NettyMessageDto messageDto = JSONObject.parseObject(messageBody, NettyMessageDto.class);
        if (isAway) { // 下线
            chatService.sendOnlineUserByUserAway(messageDto);
        } else { // 上线
            chatService.sendOnlineUser(messageDto);
        }
    }

}
